package co.yixiang.retail.biz.user.sevice.imp;

import co.yixiang.retail.biz.user.sevice.ConsumerCodeService;
import co.yixiang.retail.common.domain.CreateCode;
import co.yixiang.retail.common.utils.ConsumerCodeUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ConsumerCodeServiceImpl implements ConsumerCodeService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public String createCode(Integer cont,Long uid) {
        if(cont==null)cont = 8;
        String itemID = ConsumerCodeUtil.getItemIDRandom(cont);
        Query query = new Query(Criteria.where("uid").is(uid));
        CreateCode code = mongoTemplate.findOne(query, CreateCode.class);
        if(code != null ){
            Query query1 = new Query(Criteria.where("code").is(itemID));
            if(mongoTemplate.count(query1,CreateCode.class)>0){
                for(;;){
                    itemID = ConsumerCodeUtil.getItemIDRandom(cont);
                    Query query2 = new Query(Criteria.where("code").is(itemID));
                    if(mongoTemplate.count(query2,CreateCode.class)==0){
                        break;
                    }
                }
            }
            mongoTemplate.updateFirst(new Query(Criteria.where("uid").is(uid)),new Update().set("code",itemID),CreateCode.class);
        }else {
            code = new CreateCode();
            code.setUid(uid);
            code.setCode(itemID);
            mongoTemplate.insert(code);
        }
        return itemID;
    }
}
